<template>
  <div class="home-container">
    <!-- 顶部工具栏 -->
    <div class="toolbar">
      <div class="toolbar-left">
        <h1 class="app-title">
          <el-icon><Search /></el-icon>
          共享文件检索工具
        </h1>
        <el-tag class="path-tag" size="small">{{ config.targetPath || '未配置' }}</el-tag>
      </div>
      
      <!-- 搜索区域 -->
      <div class="toolbar-center">
        <SearchComponent 
          ref="searchComponentRef"
          @search="handleSearch"
          @clear="handleSearchClear"
        />
      </div>
      
      <div class="toolbar-right">
        <el-dropdown @command="handleMenuCommand" class="more-dropdown">
          <el-button type="text" class="more-button">
            <el-icon><More /></el-icon>
            更多
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="status">系统状态</el-dropdown-item>
              <el-dropdown-item command="refresh">刷新数据</el-dropdown-item>
              <el-dropdown-item command="stop" :disabled="!isScanning">停止扫描</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </div>
    
    <!-- 主内容区域 -->
    <div class="main-content">
      <!-- 左侧目录树 -->
      <div class="left-panel" :style="{ width: leftPanelWidth + 'px' }">
        <DirectoryTree
          ref="directoryTreeRef"
          :raw-tree-data="indexData?.tree || {}"
          :loading="isLoadingIndex"
          :statistics="indexData?.metadata || {}"
          @node-click="handleTreeNodeClick"
          @refresh="refreshData"
        />
      </div>
      
      <!-- 可拖拽的分割线 -->
      <div 
        class="resize-handle"
        @mousedown="startResize"
        :class="{ 'resizing': isResizing }"
      >
        <div class="resize-line"></div>
      </div>
      
      <!-- 右侧文件列表 -->
      <div class="right-panel">
        <!-- 面包屑导航和分组控制 -->
        <div class="content-header" v-if="selectedPath || breadcrumbPath.length > 0">
          <!-- 面包屑导航 -->
          <div class="breadcrumb-section" v-if="breadcrumbPath.length > 0">
            <el-breadcrumb separator="/">
              <el-breadcrumb-item>
                <el-button 
                  text 
                  size="small" 
                  @click="clearPathSelection"
                  style="padding: 0;"
                >
                  <el-icon><House /></el-icon>
                  全部文件
                </el-button>
              </el-breadcrumb-item>
              <el-breadcrumb-item 
                v-for="(crumb, index) in breadcrumbPath" 
                :key="index"
              >
                <el-button 
                  text 
                  size="small"
                  @click="navigateToCrumb(crumb)"
                  :class="{ 'current-crumb': crumb.isLast }"
                  style="padding: 0;"
                >
                  {{ crumb.name }}
                </el-button>
              </el-breadcrumb-item>
            </el-breadcrumb>
          </div>
          
          <!-- 分组模式控制 -->
          <div class="group-controls">
            <el-text size="small" style="margin-right: 8px;">分组方式:</el-text>
            <el-button-group size="small">
              <el-button 
                :type="groupMode === 'type' ? 'primary' : ''"
                @click="changeGroupMode('type')"
              >
                <el-icon><Grid /></el-icon>
                类型
              </el-button>
              <el-button 
                :type="groupMode === 'time' ? 'primary' : ''"
                @click="changeGroupMode('time')"
              >
                <el-icon><Clock /></el-icon>
                时间
              </el-button>
              <el-button 
                :type="groupMode === 'size' ? 'primary' : ''"
                @click="changeGroupMode('size')"
              >
                <el-icon><DataAnalysis /></el-icon>
                大小
              </el-button>
            </el-button-group>
          </div>
        </div>
        
        <!-- 文件分组显示 -->
        <div class="file-groups" v-if="selectedPath && Object.keys(fileGroups).length > 0">
          <div 
            v-for="(files, groupName) in fileGroups" 
            :key="groupName"
            class="file-group"
          >
            <div class="group-header">
              <h4 class="group-title">
                {{ groupName }}
                <el-tag size="small" type="info">{{ files.length }} 个文件</el-tag>
              </h4>
            </div>
            <div class="group-files">
              <FileList
                :files="files"
                :loading="isSearching || isLoadingIndex"
                :search-keyword="currentSearchKeyword"
                @row-click="handleFileRowClick"
                @refresh="refreshData"
                :show-header="false"
              />
            </div>
          </div>
        </div>
        
        <!-- 普通文件列表 -->
        <FileList
          v-else
          ref="fileListRef"
          :files="displayFiles"
          :loading="isSearching || isLoadingIndex"
          :search-keyword="currentSearchKeyword"
          @row-click="handleFileRowClick"
          @refresh="refreshData"
        />
      </div>
    </div>
    
    <!-- 底部状态栏 -->
    <div class="status-bar">
      <div class="status-left">
        <el-text v-if="indexData?.metadata" size="small">
          最后更新: {{ formatDateTime(indexData.metadata.lastUpdate) }}
        </el-text>
        <el-text v-if="indexData?.metadata" size="small" class="separator">|</el-text>
        <el-text v-if="indexData?.metadata" size="small">
          文件: {{ indexData.metadata.totalFiles || 0 }} 个
          <template v-if="indexData.metadata.changes && !indexData.metadata.changes.isFirstScan">
            <el-tag 
              v-if="indexData.metadata.changes.filesChanged !== 0" 
              :type="indexData.metadata.changes.filesChanged > 0 ? 'success' : 'warning'"
              size="small" 
              effect="plain"
              style="margin-left: 4px;"
            >
              {{ indexData.metadata.changes.filesChanged > 0 ? '+' : '' }}{{ indexData.metadata.changes.filesChanged }}
            </el-tag>
          </template>
        </el-text>
        <el-text v-if="indexData?.metadata" size="small" class="separator">|</el-text>
        <el-text v-if="indexData?.metadata" size="small">
          文件夹: {{ indexData.metadata.totalFolders || 0 }} 个
          <template v-if="indexData.metadata.changes && !indexData.metadata.changes.isFirstScan">
            <el-tag 
              v-if="indexData.metadata.changes.foldersChanged !== 0" 
              :type="indexData.metadata.changes.foldersChanged > 0 ? 'success' : 'warning'"
              size="small" 
              effect="plain"
              style="margin-left: 4px;"
            >
              {{ indexData.metadata.changes.foldersChanged > 0 ? '+' : '' }}{{ indexData.metadata.changes.foldersChanged }}
            </el-tag>
          </template>
        </el-text>
      </div>
      
      <div class="status-right">
        <el-text v-if="isScanning" size="small" type="primary">
          <el-icon class="loading-icon"><Loading /></el-icon>
          {{ scanStatus?.currentPath || '正在自动扫描...' }}
        </el-text>
        <el-text v-else-if="indexData" size="small" type="success">
          <el-icon><Check /></el-icon>
          就绪 (自动更新已启用)
        </el-text>
        <el-text v-else size="small" type="info">
          <el-icon><Loading /></el-icon>
          正在自动初始化...
        </el-text>
      </div>
    </div>
    
    <!-- 扫描进度通知 -->
    <!-- 扫描状态指示器 (轻量化显示，不阻塞操作) -->
    <div v-if="isScanning" class="scan-indicator">
      <el-tooltip 
        effect="dark" 
        placement="bottom"
        :show-after="500"
      >
        <template #content>
          <div class="scan-tooltip">
            <div class="scan-info-item">
              <strong>扫描状态：</strong>进行中
            </div>
            <div class="scan-info-item" v-if="scanStats.currentStartTime">
              <strong>开始时间：</strong>{{ formatTime(scanStats.currentStartTime) }}
            </div>
            <div class="scan-info-item" v-if="scanStats.currentStartTime">
              <strong>已用时长：</strong>{{ formatDuration(Date.now() - scanStats.currentStartTime) }}
            </div>
            <div class="scan-info-item" v-if="scanStats.currentProgress > 0">
              <strong>扫描进度：</strong>{{ scanStats.currentProgress }}%
              <span v-if="scanStats.lastScanFileCount > 0">
                (基于上次{{ scanStats.lastScanFileCount }}个文件)
              </span>
            </div>
            <div class="scan-info-item">
              <strong>今日扫描：</strong>第 {{ scanStats.todayCount }} 次
            </div>
            <div class="scan-info-item" v-if="scanStats.lastScanTime">
              <strong>上次扫描：</strong>{{ formatTime(scanStats.lastScanTime) }}
            </div>
            <div class="scan-info-item" v-if="scanStats.lastScanResult">
              <strong>上次结果：</strong>
              <span :class="scanStats.lastScanResult === 'success' ? 'text-success' : 'text-error'">
                {{ scanStats.lastScanResult === 'success' ? '成功' : '失败' }}
              </span>
            </div>
            <div class="scan-info-item" v-if="scanStats.lastError">
              <strong>失败原因：</strong>{{ scanStats.lastError }}
            </div>
            <div class="scan-info-item" v-if="scanStatus?.currentPath">
              <strong>当前扫描：</strong>{{ scanStatus.currentPath }}
            </div>
          </div>
        </template>
        <el-tag type="primary" size="small" class="scan-tag">
          <el-icon class="is-loading"><Loading /></el-icon>
          后台扫描中 {{ scanStatus?.progress ? Math.round(scanStatus.progress) + '%' : '' }}
        </el-tag>
      </el-tooltip>
    </div>
    
    <!-- 系统状态对话框 -->
    <el-dialog
      v-model="statusDialogVisible"
      title="系统状态"
      width="600px"
      :close-on-click-modal="false"
    >
      <div v-if="systemStatus">
        <el-descriptions title="服务器状态" :column="2" border>
          <el-descriptions-item label="运行时间">
            {{ formatDuration(systemStatus.server?.uptime * 1000) }}
          </el-descriptions-item>
          <el-descriptions-item label="版本">
            {{ systemStatus.server?.version || '1.0.0' }}
          </el-descriptions-item>
        </el-descriptions>
        
        <el-descriptions title="扫描状态" :column="2" border style="margin-top: 20px;">
          <el-descriptions-item label="扫描状态">
            <el-tag :type="systemStatus.scan?.isScanning ? 'primary' : 'success'">
              {{ systemStatus.scan?.isScanning ? '扫描中' : '就绪' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="当前任务ID">
            {{ systemStatus.scan?.currentScanId || '无' }}
          </el-descriptions-item>
          <el-descriptions-item label="手动操作">
            <el-button 
              size="small"
              type="primary" 
              @click="startScan"
              :loading="isScanning"
              :disabled="isScanning"
            >
              <el-icon><Refresh /></el-icon>
              {{ isScanning ? '扫描中...' : '手动扫描' }}
            </el-button>
          </el-descriptions-item>
        </el-descriptions>
        
        <el-descriptions title="索引状态" :column="2" border style="margin-top: 20px;">
          <el-descriptions-item label="索引状态">
            <el-tag :type="systemStatus.index?.isLoaded ? 'success' : 'warning'">
              {{ systemStatus.index?.isLoaded ? '已加载' : '未加载' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="关键词数量">
            {{ systemStatus.index?.searchIndex?.totalKeywords || 0 }}
          </el-descriptions-item>
        </el-descriptions>
      </div>
      
      <template #footer>
        <el-button @click="statusDialogVisible = false">关闭</el-button>
        <el-button @click="showScanLogs" :disabled="!scanStats.lastError">查看错误日志</el-button>
        <el-button type="primary" @click="refreshSystemStatus">刷新状态</el-button>
      </template>
    </el-dialog>
    
    <!-- 扫描日志对话框 -->
    <el-dialog
      v-model="scanLogsDialogVisible"
      title="扫描错误日志"
      width="800px"
      :close-on-click-modal="false"
    >
      <div class="scan-logs-container">
        <div class="logs-header">
          <el-text size="small" type="info">最近的扫描错误日志，帮助分析扫描失败原因：</el-text>
          <el-button size="small" @click="refreshScanLogs" :loading="isLoadingLogs">
            <el-icon><Refresh /></el-icon>
            刷新日志
          </el-button>
        </div>
        <div class="logs-content">
          <pre v-if="scanLogs.length > 0" class="logs-text">{{ scanLogs.join('\n') }}</pre>
          <el-empty v-else description="暂无错误日志" />
        </div>
      </div>
      
      <template #footer>
        <el-button @click="scanLogsDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onBeforeUnmount, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { 
  Search, 
  Refresh, 
  RefreshRight, 
  More, 
  Loading, 
  Check, 
  Warning,
  House,
  Grid,
  Clock,
  DataAnalysis
} from '@element-plus/icons-vue'
import SearchComponent from '../components/SearchComponent.vue'
import DirectoryTree from '../components/DirectoryTree.vue'
import FileList from '../components/FileList.vue'
import { fileApi } from '../api/fileApi'
import { formatDateTime, formatDuration } from '../utils/fileUtils'

// 组件引用
const searchComponentRef = ref(null)
const directoryTreeRef = ref(null)
const fileListRef = ref(null)

// 响应式数据
const indexData = ref(null)              // 索引数据
const isLoadingIndex = ref(false)        // 加载索引状态
const isScanning = ref(false)            // 扫描状态
const isSearching = ref(false)           // 搜索状态
const scanStatus = ref(null)             // 扫描状态信息
const scanPollingTimer = ref(null)      // 扫描轮询定时器
const lastScanTime = ref(0)              // 最后一次扫描时间，防重复扫描
const autoScanTimer = ref(null)          // 自动扫描定时器
const autoScanInterval = 30 * 60 * 1000  // 自动扫描间隔：30分钟
const eventListeners = []                // 存储事件监听器，用于清理

// 扫描统计信息
const scanStats = reactive({
  todayCount: 0,           // 今日扫描次数
  currentStartTime: null,  // 当前扫描开始时间
  lastScanResult: null,    // 上次扫描结果 (success/failed)
  lastScanTime: null,      // 上次扫描完成时间
  lastError: null,         // 最后错误信息
  lastScanFileCount: 0,    // 上次扫描的文件数量，用于计算进度
  currentProgress: 0       // 当前扫描进度百分比
})
const systemStatus = ref(null)           // 系统状态
const statusDialogVisible = ref(false)   // 状态对话框显示状态
const scanLogsDialogVisible = ref(false) // 扫描日志对话框显示状态
const scanLogs = ref([])                  // 扫描日志
const isLoadingLogs = ref(false)         // 加载日志状态

// 搜索相关数据
const searchResults = ref([])            // 搜索结果
const currentSearchKeyword = ref('')     // 当前搜索关键词
const allFiles = ref([])                 // 所有文件数据

// 新增：上下文搜索和文件分组
const selectedPath = ref('')             // 当前选中的路径上下文
const fileGroups = ref({})               // 文件分组数据
const groupMode = ref('type')            // 分组模式：type, time, size
const breadcrumbPath = ref([])           // 面包屑路径

// 新增：分割线拖拽调整
const leftPanelWidth = ref(480)          // 左侧面板宽度
const isResizing = ref(false)            // 是否正在调整大小
const minLeftWidth = 300                 // 左侧面板最小宽度
const maxLeftWidth = 800                 // 左侧面板最大宽度

// 配置信息
const config = reactive({
  targetPath: '',
  autoRefresh: false
})

// 计算属性
const displayFiles = computed(() => {
  let files = []
  
  if (searchResults.value.length > 0) {
    // 有搜索结果时显示搜索结果
    files = searchResults.value
  } else if (selectedPath.value) {
    // 有选中路径时显示该路径下的文件
    files = getFilesByPath(selectedPath.value)
  } else {
    // 默认显示所有文件
    files = allFiles.value
  }
  
  return files
})

// 根据路径获取文件
const getFilesByPath = (path) => {
  if (!path || !allFiles.value) return []
  
  return allFiles.value.filter(file => {
    return file.path.includes(path) || file.parent.includes(path)
  })
}

// 组件挂载时初始化
onMounted(async () => {
  console.log('主页面组件已挂载')
  
  // 恢复面板宽度
  restorePanelWidth()
  
  await initializeApp()
  
  // 初始化扫描统计信息
  initScanStats()
  
  // 启动智能扫描系统
  startAutoScanSystem()
  
  // 启动扫描状态监控
  startScanStatusMonitoring()
  
  // 记录用户活动
  trackUserActivity()
})

// 组件卸载前清理
onBeforeUnmount(() => {
  console.log('主页面组件卸载，清理资源...')
  
  // 停止自动扫描系统
  stopAutoScanSystem()
  
  // 清理扫描轮询
  stopScanStatusPolling()
  
  // 清理所有事件监听器
  eventListeners.forEach(({ type, handler, target }) => {
    target.removeEventListener(type, handler)
  })
  eventListeners.length = 0
  
  console.log('所有资源清理完成')
})

/**
 * 初始化应用
 */
async function initializeApp() {
  try {
    // 加载配置信息
    await loadConfig()
    
    // 加载文件索引
    await loadFileIndex()
    
  } catch (error) {
    console.error('初始化应用失败:', error)
    ElMessage.error('初始化失败: ' + error.message)
  }
}

/**
 * 加载配置信息
 */
async function loadConfig() {
  try {
    const response = await fileApi.getConfig()
    if (response.success) {
      config.targetPath = response.data.scan.targetPath
      config.autoRefresh = response.data.ui.autoRefresh
      console.log('配置加载成功:', response.data)
    }
  } catch (error) {
    console.error('加载配置失败:', error)
  }
}

/**
 * 加载文件索引
 */
async function loadFileIndex() {
  try {
    isLoadingIndex.value = true
    console.log('开始加载文件索引...')
    
    const response = await fileApi.getFileIndex()
    
    if (response.success && response.data) {
      indexData.value = response.data
      allFiles.value = response.data.files || []
      
      console.log('文件索引加载成功:', {
        totalFiles: response.data.files?.length || 0,
        totalFolders: response.data.folders?.length || 0
      })
      
      // 检查数据是否过时，如果过时则后台自动更新
      checkAndUpdateIndex()
    } else {
      console.log('索引文件不存在:', response.message)
      ElMessage.info('正在后台扫描文件，请稍候...')
      // 后台启动扫描，不阻塞界面
      startBackgroundScan()
    }
    
  } catch (error) {
    console.error('加载索引失败:', error)
    ElMessage.error('加载索引失败: ' + error.message)
  } finally {
    isLoadingIndex.value = false
  }
}

/**
 * 后台扫描（不阻塞用户操作，避免打断）
 */
async function startBackgroundScan() {
  try {
    const now = Date.now()
    
    // 防止频繁扫描：如果正在扫描或刚扫描完成不久，不启动新扫描
    if (isScanning.value) {
      console.log('扫描已在进行中，避免打断当前扫描')
      return { success: false, reason: 'already_scanning' }
    }
    
    if (now - lastScanTime.value < 30000) {
      console.log('扫描间隔过短，跳过本次扫描')
      return { success: false, reason: 'too_frequent' }
    }
    
    // 记录扫描开始
    lastScanTime.value = now
    scanStats.currentStartTime = now
    scanStats.todayCount += 1
    scanStats.lastError = null
    
    console.log(`启动后台扫描 (今日第${scanStats.todayCount}次)...`)
    
    const response = await fileApi.startScan({
      path: config.targetPath,
      force: false  // 改为false，避免强制打断可能正在进行的扫描
    })
    
    if (response.success) {
      console.log('后台扫描启动成功')
      isScanning.value = true
      
      // 保存统计信息
      saveScanStats()
      
      // 开始监控扫描状态
      startScanStatusMonitoring()
      
      return { success: true }
    } else {
      throw new Error(response.message)
    }
  } catch (error) {
    console.error('启动后台扫描失败:', error)
    
    // 记录失败信息
    scanStats.lastScanResult = 'failed'
    scanStats.lastError = error.message
    scanStats.lastScanTime = Date.now()
    scanStats.currentStartTime = null
    
    saveScanStats()
    
    return { success: false, error: error.message }
  }
}

/**
 * 检查并更新索引
 */
async function checkAndUpdateIndex() {
  try {
    // 检查索引是否需要更新（可以基于文件修改时间等）
    const shouldUpdate = await shouldUpdateIndex()
    if (shouldUpdate) {
      ElMessage.info({
        message: '检测到文件变化，正在后台更新索引...',
        duration: 2000
      })
      startBackgroundScan()
    }
  } catch (error) {
    console.error('检查索引更新失败:', error)
  }
}

/**
 * 启动自动扫描系统
 */
function startAutoScanSystem() {
  console.log('启动智能扫描系统...')
  
  // 清除之前的定时器
  if (autoScanTimer.value) {
    clearInterval(autoScanTimer.value)
  }
  
  // 设置定时扫描（每30分钟）
  autoScanTimer.value = setInterval(() => {
    if (!isScanning.value && shouldPerformAutoScan()) {
      console.log('执行定时自动扫描')
      performIntelligentScan()
    }
  }, autoScanInterval)
  
  // 页面活跃时检查是否需要扫描
  const visibilityHandler = () => {
    if (!document.hidden && shouldPerformAutoScan()) {
      console.log('页面重新激活，检查是否需要扫描')
      performIntelligentScan()
    }
  }
  document.addEventListener('visibilitychange', visibilityHandler)
  eventListeners.push({ type: 'visibilitychange', handler: visibilityHandler, target: document })
}

/**
 * 停止自动扫描系统
 */
function stopAutoScanSystem() {
  if (autoScanTimer.value) {
    clearInterval(autoScanTimer.value)
    autoScanTimer.value = null
  }
}

/**
 * 判断是否应该执行自动扫描
 */
function shouldPerformAutoScan() {
  const now = Date.now()
  const timeSinceLastScan = now - lastScanTime.value
  
  // 至少1小时后才自动扫描
  return timeSinceLastScan > 60 * 60 * 1000
}

/**
 * 智能扫描（根据策略决定扫描方式）
 */
async function performIntelligentScan() {
  try {
    // 检查系统负载和用户活动
    if (isUserActive() && !shouldScanInBackground()) {
      console.log('用户活跃且系统繁忙，延迟扫描')
      return
    }
    
    // 执行扫描
    await startBackgroundScan()
    
  } catch (error) {
    console.error('智能扫描失败:', error)
  }
}

/**
 * 检查用户是否活跃
 */
function isUserActive() {
  try {
    // 检查最近是否有用户交互
    const lastActivity = sessionStorage.getItem('lastActivity')
    if (!lastActivity) return false
    
    const timeSinceActivity = Date.now() - parseInt(lastActivity)
    return timeSinceActivity < 5 * 60 * 1000 // 5分钟内有活动
  } catch (error) {
    // sessionStorage失败时，默认认为用户活跃
    return true
  }
}

/**
 * 判断是否应该后台扫描
 */
function shouldScanInBackground() {
  // 简单策略：非工作时间或用户不活跃时扫描
  const hour = new Date().getHours()
  return hour < 8 || hour > 18 || !isUserActive()
}

/**
 * 判断是否需要更新索引
 */
async function shouldUpdateIndex() {
  try {
    // 检查索引文件的最后修改时间
    const response = await fileApi.getFileIndex()
    if (response.success && response.data?.metadata?.lastUpdate) {
      const lastUpdate = new Date(response.data.metadata.lastUpdate).getTime()
      const now = Date.now()
      
      // 如果索引超过4小时没更新，建议扫描
      return (now - lastUpdate) > 4 * 60 * 60 * 1000
    }
    
    return false
  } catch (error) {
    return false
  }
}

/**
 * 追踪用户活动
 */
function trackUserActivity() {
  const updateActivity = () => {
    try {
      sessionStorage.setItem('lastActivity', Date.now().toString())
    } catch (error) {
      // sessionStorage失败不影响核心功能
    }
  }
  
  // 监听各种用户交互事件
  const events = ['click', 'keydown', 'scroll', 'mousemove']
  events.forEach(event => {
    document.addEventListener(event, updateActivity, { passive: true })
    eventListeners.push({ type: event, handler: updateActivity, target: document })
  })
  
  // 初始化活动时间
  updateActivity()
}

/**
 * 格式化时间显示
 */
function formatTime(timestamp) {
  if (!timestamp) return ''
  const date = new Date(timestamp)
  return date.toLocaleTimeString('zh-CN', { 
    hour12: false,
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}


/**
 * 初始化扫描统计信息
 */
function initScanStats() {
  try {
    const today = new Date().toDateString()
    const savedStats = localStorage.getItem('scanStats')
    
    if (savedStats) {
      const parsed = JSON.parse(savedStats)
      if (parsed.date === today) {
        // 同一天，恢复统计信息
        Object.assign(scanStats, {
          todayCount: parsed.todayCount || 0,
          lastScanResult: parsed.lastScanResult,
          lastScanTime: parsed.lastScanTime,
          lastError: parsed.lastError,
          lastScanFileCount: parsed.lastScanFileCount || 0
        })
      }
    }
  } catch (error) {
    console.warn('恢复扫描统计失败:', error)
    // localStorage失败不影响核心功能，使用默认值
  }
}

/**
 * 更新扫描进度
 */
function updateScanProgress(scanData) {
  if (!scanData || !scanStats.lastScanFileCount) {
    scanStats.currentProgress = 0
    return
  }
  
  // 根据已处理文件数量计算进度
  const processedCount = scanData.processedFiles || scanData.scannedCount || 0
  if (processedCount > 0 && scanStats.lastScanFileCount > 0) {
    const progress = Math.round((processedCount / scanStats.lastScanFileCount) * 100)
    scanStats.currentProgress = Math.min(progress, 150) // 最大显示150%，表示文件增加了
  }
}

/**
 * 保存扫描统计信息
 */
function saveScanStats() {
  try {
    const today = new Date().toDateString()
    const statsToSave = {
      date: today,
      todayCount: scanStats.todayCount,
      lastScanResult: scanStats.lastScanResult,
      lastScanTime: scanStats.lastScanTime,
      lastError: scanStats.lastError,
      lastScanFileCount: scanStats.lastScanFileCount
    }
    
    localStorage.setItem('scanStats', JSON.stringify(statsToSave))
  } catch (error) {
    console.warn('保存扫描统计失败:', error)
    // localStorage失败不影响核心功能
  }
}

/**
 * 显示扫描日志
 */
async function showScanLogs() {
  scanLogsDialogVisible.value = true
  await refreshScanLogs()
}

/**
 * 刷新扫描日志
 */
async function refreshScanLogs() {
  try {
    isLoadingLogs.value = true
    const response = await fileApi.getScanLogs({ lines: 50 })
    
    if (response.success && response.data) {
      scanLogs.value = Array.isArray(response.data) ? response.data : [response.data]
    } else {
      scanLogs.value = ['暂无可用的错误日志']
    }
  } catch (error) {
    console.error('获取扫描日志失败:', error)
    scanLogs.value = [`获取日志失败: ${error.message}`]
  } finally {
    isLoadingLogs.value = false
  }
}

/**
 * 开始文件扫描
 */
async function startScan() {
  try {
    isScanning.value = true
    console.log('开始文件扫描...')
    
    const response = await fileApi.startScan({
      path: config.targetPath,
      force: true
    })
    
    if (response.success) {
      ElMessage.success('文件扫描已启动')
      
      // 开始监控扫描进度
      monitorScanProgress(response.scanId)
    } else {
      throw new Error(response.message)
    }
    
  } catch (error) {
    console.error('启动扫描失败:', error)
    ElMessage.error('启动扫描失败: ' + error.message)
    isScanning.value = false
  }
}

/**
 * 监控扫描进度
 */
async function monitorScanProgress(scanId) {
  const checkProgress = async () => {
    try {
      const response = await fileApi.getScanStatus(scanId)
      
      if (response.success) {
        scanStatus.value = response.data
        
        if (response.data.isScanning) {
          // 继续监控
          setTimeout(checkProgress, 2000)
        } else {
          // 扫描完成
          isScanning.value = false
          scanStatus.value = null
          
          ElMessage.success('文件扫描完成')
          
          // 重新加载索引数据
          await loadFileIndex()
        }
      }
    } catch (error) {
      console.error('获取扫描状态失败:', error)
      isScanning.value = false
    }
  }
  
  // 开始检查进度
  setTimeout(checkProgress, 1000)
}

/**
 * 停止扫描
 */
async function stopScan() {
  try {
    const response = await fileApi.stopScan()
    
    if (response.success) {
      ElMessage.success('扫描停止请求已发送')
      isScanning.value = false
      scanStatus.value = null
    }
  } catch (error) {
    console.error('停止扫描失败:', error)
    ElMessage.error('停止扫描失败: ' + error.message)
  }
}

/**
 * 刷新数据
 */
async function refreshData() {
  await loadFileIndex()
}

/**
 * 静默加载文件索引（不显示加载提示）
 */
async function silentLoadFileIndex() {
  try {
    console.log('静默更新文件索引...')
    
    const response = await fileApi.getFileIndex()
    
    if (response.success && response.data) {
      indexData.value = response.data
      allFiles.value = response.data.files || []
      
      console.log('文件索引静默更新成功:', {
        totalFiles: response.data.files?.length || 0,
        totalFolders: response.data.folders?.length || 0
      })
    }
    
  } catch (error) {
    console.error('静默加载索引失败:', error)
    // 失败时不影响用户操作
  }
}

/**
 * 处理搜索
 */
async function handleSearch(searchParams) {
  try {
    isSearching.value = true
    currentSearchKeyword.value = searchParams.keyword
    
    // 智能搜索：如果有选中路径，在该路径下搜索
    const enhancedParams = { ...searchParams }
    if (selectedPath.value) {
      // 将路径上下文添加到搜索中
      enhancedParams.pathContext = selectedPath.value
      console.log('在选中路径下搜索:', selectedPath.value)
    }
    
    console.log('执行搜索:', enhancedParams)
    
    const response = await fileApi.searchFiles(enhancedParams)
    
    if (response.success) {
      searchResults.value = response.data || []
      
      // 如果有路径上下文但搜索结果为空，提供智能建议
      if (selectedPath.value && searchResults.value.length === 0) {
        // 建议在全局搜索
        ElMessage.warning(`在当前路径未找到结果，建议点击"全部文件"进行全局搜索`)
      }
      
      // 更新搜索组件的结果
      if (searchComponentRef.value) {
        searchComponentRef.value.updateSearchResults(searchResults.value)
      }
      
      console.log('搜索完成:', searchResults.value.length, '个结果')
      
      // 清除分组显示，优先显示搜索结果
      fileGroups.value = {}
      
    } else {
      throw new Error(response.message)
    }
    
  } catch (error) {
    console.error('搜索失败:', error)
    ElMessage.error('搜索失败: ' + error.message)
    searchResults.value = []
  } finally {
    isSearching.value = false
    
    if (searchComponentRef.value) {
      searchComponentRef.value.setSearching(false)
    }
  }
}

/**
 * 处理搜索清除
 */
function handleSearchClear() {
  searchResults.value = []
  currentSearchKeyword.value = ''
  console.log('搜索结果已清除')
}

/**
 * 处理目录树节点点击
 */
function handleTreeNodeClick(nodeInfo) {
  console.log('目录树节点点击:', nodeInfo)
  
  if (nodeInfo.type === 'folder') {
    // 设置选中路径，触发文件列表更新
    selectedPath.value = nodeInfo.path
    
    // 构建面包屑路径
    buildBreadcrumbPath(nodeInfo.path)
    
    // 清除搜索结果，显示路径下的文件
    searchResults.value = []
    currentSearchKeyword.value = ''
    
    // 更新搜索组件状态
    if (searchComponentRef.value) {
      searchComponentRef.value.clearResults()
    }
    
    // 分组显示文件
    groupFilesByMode(getFilesByPath(nodeInfo.path))
    
    ElMessage.success(`已选择路径: ${nodeInfo.data.name} (${getFilesByPath(nodeInfo.path).length} 个文件)`)
  }
}

/**
 * 构建面包屑路径
 */
function buildBreadcrumbPath(path) {
  if (!path) {
    breadcrumbPath.value = []
    return
  }
  
  const parts = path.split('/').filter(part => part.trim())
  const crumbs = []
  let currentPath = ''
  
  parts.forEach((part, index) => {
    currentPath += (index === 0 ? '' : '/') + part
    crumbs.push({
      name: part,
      path: currentPath,
      isLast: index === parts.length - 1
    })
  })
  
  breadcrumbPath.value = crumbs
}

/**
 * 按模式分组文件
 */
function groupFilesByMode(files) {
  if (!files || files.length === 0) {
    fileGroups.value = {}
    return
  }
  
  const groups = {}
  
  if (groupMode.value === 'type') {
    // 按文件类型分组
    files.forEach(file => {
      const type = file.type || 'other'
      if (!groups[type]) {
        groups[type] = []
      }
      groups[type].push(file)
    })
  } else if (groupMode.value === 'time') {
    // 按修改时间分组
    const now = new Date()
    files.forEach(file => {
      const modifiedDate = new Date(file.modified)
      const diffDays = Math.floor((now - modifiedDate) / (1000 * 60 * 60 * 24))
      
      let timeGroup = ''
      if (diffDays === 0) {
        timeGroup = '今天'
      } else if (diffDays <= 7) {
        timeGroup = '本周'
      } else if (diffDays <= 30) {
        timeGroup = '本月'
      } else {
        timeGroup = '较早'
      }
      
      if (!groups[timeGroup]) {
        groups[timeGroup] = []
      }
      groups[timeGroup].push(file)
    })
  } else if (groupMode.value === 'size') {
    // 按文件大小分组
    files.forEach(file => {
      const size = file.size || 0
      let sizeGroup = ''
      
      if (size < 1024 * 1024) {
        sizeGroup = '小文件 (<1MB)'
      } else if (size < 10 * 1024 * 1024) {
        sizeGroup = '中等文件 (1-10MB)'
      } else {
        sizeGroup = '大文件 (>10MB)'
      }
      
      if (!groups[sizeGroup]) {
        groups[sizeGroup] = []
      }
      groups[sizeGroup].push(file)
    })
  }
  
  fileGroups.value = groups
}

/**
 * 切换分组模式
 */
function changeGroupMode(mode) {
  groupMode.value = mode
  const currentFiles = selectedPath.value ? getFilesByPath(selectedPath.value) : displayFiles.value
  groupFilesByMode(currentFiles)
}

/**
 * 清除路径选择
 */
function clearPathSelection() {
  selectedPath.value = ''
  breadcrumbPath.value = []
  fileGroups.value = {}
  searchResults.value = []
  currentSearchKeyword.value = ''
  
  // 清除目录树的选中状态
  if (directoryTreeRef.value) {
    // 由于移除了复选框，这里不需要清除选中状态
    // 用户可以通过点击其他节点来改变选中状态
  }
  
  if (searchComponentRef.value) {
    searchComponentRef.value.clearResults()
  }
  
  ElMessage.info('已返回全部文件视图')
}

/**
 * 导航到面包屑路径
 */
function navigateToCrumb(crumb) {
  if (!crumb.isLast) {
    selectedPath.value = crumb.path
    buildBreadcrumbPath(crumb.path)
    groupFilesByMode(getFilesByPath(crumb.path))
    
    ElMessage.success(`已切换到: ${crumb.name}`)
  }
}

/**
 * 处理文件行点击
 */
function handleFileRowClick(file) {
  console.log('文件行点击:', file)
  ElMessage.info(`点击了文件: ${file.name}`)
}

/**
 * 处理菜单命令
 */
async function handleMenuCommand(command) {
  switch (command) {
    case 'status':
      await showSystemStatus()
      break
    case 'refresh':
      await refreshData()
      break
    case 'stop':
      await stopScan()
      break
    default:
      console.log('未知命令:', command)
  }
}

/**
 * 显示系统状态
 */
async function showSystemStatus() {
  try {
    statusDialogVisible.value = true
    await refreshSystemStatus()
  } catch (error) {
    console.error('获取系统状态失败:', error)
    ElMessage.error('获取系统状态失败: ' + error.message)
  }
}

/**
 * 刷新系统状态
 */
async function refreshSystemStatus() {
  try {
    const response = await fileApi.getSystemStatus()
    
    if (response.success) {
      systemStatus.value = response.data
      console.log('系统状态:', systemStatus.value)
    } else {
      throw new Error(response.message)
    }
  } catch (error) {
    console.error('刷新系统状态失败:', error)
    ElMessage.error('刷新系统状态失败: ' + error.message)
  }
}

/**
 * 启动扫描状态监控
 */
function startScanStatusMonitoring() {
  // 定期检查扫描状态
  const checkScanStatus = async () => {
    try {
      const response = await fileApi.getScanStatus()
      
      if (response.success && response.data.isScanning) {
        if (!isScanning.value) {
          // 发现有自动扫描在进行
          isScanning.value = true
          ElMessage.info('检测到自动扫描正在进行中...')
        }
        
        scanStatus.value = response.data
        
        // 计算扫描进度
        updateScanProgress(response.data)
        
        // 继续监控
        setTimeout(checkScanStatus, 3000)
      } else if (response.success && !response.data.isScanning && isScanning.value) {
        // 扫描完成
        isScanning.value = false
        scanStatus.value = null
        
        // 记录扫描成功
        scanStats.lastScanResult = 'success'
        scanStats.lastScanTime = Date.now()
        const duration = scanStats.currentStartTime ? Date.now() - scanStats.currentStartTime : 0
        scanStats.currentStartTime = null
        
        // 保存统计信息
        saveScanStats()
        
        // 提示用户数据已更新
        ElMessage({
          message: `文件扫描完成 (用时${formatDuration(duration)})，数据已更新`,
          type: 'success',
          showClose: true,
          duration: 5000
        })
        
        // 静默重新加载索引数据，不阻塞用户操作
        await silentLoadFileIndex()
        
        // 更新文件数量统计（用于下次计算进度）
        if (indexData.value?.files) {
          scanStats.lastScanFileCount = indexData.value.files.length
          saveScanStats()
        }
        
        // 清理进度显示
        scanStats.currentProgress = 0
      }
    } catch (error) {
      // 静默处理错误，避免过多提示
      console.warn('检查扫描状态失败:', error)
    }
  }
  
  // 启动监控
  setTimeout(checkScanStatus, 2000)
}

/**
 * 开始调整面板大小
 */
function startResize(event) {
  isResizing.value = true
  const startX = event.clientX
  const startWidth = leftPanelWidth.value
  
  // 添加全局鼠标移动和释放事件
  const handleMouseMove = (e) => {
    if (!isResizing.value) return
    
    const diff = e.clientX - startX
    const newWidth = startWidth + diff
    
    // 限制在最小和最大宽度之间
    if (newWidth >= minLeftWidth && newWidth <= maxLeftWidth) {
      leftPanelWidth.value = newWidth
    }
  }
  
  const handleMouseUp = () => {
    isResizing.value = false
    document.removeEventListener('mousemove', handleMouseMove)
    document.removeEventListener('mouseup', handleMouseUp)
    
    // 保存用户偏好到localStorage
    localStorage.setItem('fileSearch_leftPanelWidth', leftPanelWidth.value.toString())
  }
  
  document.addEventListener('mousemove', handleMouseMove)
  document.addEventListener('mouseup', handleMouseUp)
}

/**
 * 从localStorage恢复面板宽度
 */
function restorePanelWidth() {
  const savedWidth = localStorage.getItem('fileSearch_leftPanelWidth')
  if (savedWidth) {
    const width = parseInt(savedWidth)
    if (width >= minLeftWidth && width <= maxLeftWidth) {
      leftPanelWidth.value = width
    }
  }
}
</script>

<style scoped>
.home-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f5f7fa;
}

.toolbar {
  display: flex;
  align-items: center;
  padding: 16px 24px;
  background: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%);
  border-bottom: 1px solid rgba(102, 126, 234, 0.1);
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.04);
  gap: 24px;
  backdrop-filter: blur(10px);
}

.toolbar-left {
  display: flex;
  align-items: center;
  gap: 12px;
  flex-shrink: 0;
}

.toolbar-center {
  flex: 1;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 0 32px;
  min-width: 0;
  max-width: 800px;
}

.app-title {
  margin: 0;
  font-size: 18px;
  font-weight: 700;
  color: #2c3e50;
  display: flex;
  align-items: center;
  gap: 8px;
  letter-spacing: -0.02em;
}

.app-title .el-icon {
  color: #667eea;
  font-size: 20px;
}

.path-tag {
  background: rgba(102, 126, 234, 0.08);
  border: 1px solid rgba(102, 126, 234, 0.2);
  color: #667eea;
  font-weight: 500;
  border-radius: 12px;
  font-size: 11px;
  max-width: 200px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.toolbar-right {
  display: flex;
  align-items: center;
  gap: 8px;
  flex-shrink: 0;
  margin-left: auto;
}

.more-dropdown {
  margin-left: 16px;
}

.more-button {
  padding: 8px 16px;
  border-radius: 10px;
  color: #666;
  font-size: 14px;
  transition: all 0.3s ease;
}

.more-button:hover {
  background: rgba(102, 126, 234, 0.08);
  color: #667eea;
}


.main-content {
  flex: 1;
  display: flex;
  padding: 16px 20px;
  overflow: hidden;
  gap: 0;
}

.left-panel {
  flex-shrink: 0;
  min-width: 300px;
  max-width: 800px;
}

.resize-handle {
  width: 6px;
  cursor: col-resize;
  position: relative;
  background-color: transparent;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: background-color 0.2s ease;
  margin: 0 8px;
}

.resize-handle:hover {
  background-color: #e4e7ed;
}

.resize-handle.resizing {
  background-color: #409eff;
}

.resize-line {
  width: 2px;
  height: 100%;
  background-color: #dcdfe6;
  border-radius: 1px;
  transition: background-color 0.2s ease;
}

.resize-handle:hover .resize-line,
.resize-handle.resizing .resize-line {
  background-color: #409eff;
}

.right-panel {
  flex: 1;
  min-width: 0;
  overflow-y: auto;
  height: 100%;
}

.status-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 20px;
  background-color: #fff;
  border-top: 1px solid #e4e7ed;
  font-size: 12px;
}

.status-left {
  display: flex;
  align-items: center;
  gap: 8px;
}

.status-right {
  display: flex;
  align-items: center;
  gap: 8px;
}

.separator {
  color: #c0c4cc;
}

.loading-icon {
  animation: rotating 2s linear infinite;
}

@keyframes rotating {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

/* 扫描状态指示器 */
.scan-indicator {
  position: fixed;
  top: 20px;
  right: 20px;
  z-index: 1000;
  animation: fadeInOut 0.3s ease-in-out;
}

.scan-tag {
  padding: 8px 12px;
  font-size: 12px;
  background: linear-gradient(45deg, #409eff, #67c23a);
  color: white;
  border: none;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.scan-tag .el-icon {
  margin-right: 4px;
}

@keyframes fadeInOut {
  from { opacity: 0; transform: translateX(20px); }
  to { opacity: 1; transform: translateX(0); }
}

/* 扫描提示框样式 */
.scan-tooltip {
  font-size: 12px;
  line-height: 1.5;
  max-width: 300px;
}

.scan-info-item {
  margin: 4px 0;
  display: flex;
  align-items: flex-start;
  word-break: break-all;
}

.scan-info-item strong {
  flex-shrink: 0;
  margin-right: 4px;
  color: #fff;
}

.text-success {
  color: #67c23a;
}

.text-error {
  color: #f56c6c;
}

/* 扫描日志样式 */
.scan-logs-container {
  max-height: 500px;
  overflow: hidden;
}

.logs-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
  padding-bottom: 8px;
  border-bottom: 1px solid #ebeef5;
}

.logs-content {
  max-height: 400px;
  overflow-y: auto;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  background-color: #f5f7fa;
}

.logs-text {
  margin: 0;
  padding: 12px;
  font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
  font-size: 12px;
  line-height: 1.4;
  color: #606266;
  white-space: pre-wrap;
  word-break: break-all;
}

.scan-progress p {
  margin: 5px 0;
}

.scan-path {
  font-size: 12px;
  color: #666;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

/* 新增样式：内容头部和分组 */
.content-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  background-color: #fafbfc;
  border: 1px solid #e4e7ed;
  border-radius: 6px 6px 0 0;
  margin-bottom: 16px;
}

.breadcrumb-section {
  flex: 1;
}

.group-controls {
  display: flex;
  align-items: center;
  flex-shrink: 0;
}

.current-crumb {
  font-weight: 600;
  color: #409eff;
}

.file-groups {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.file-group {
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  overflow: hidden;
}

.group-header {
  background-color: #f5f7fa;
  padding: 12px 16px;
  border-bottom: 1px solid #e4e7ed;
}

.group-title {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  display: flex;
  align-items: center;
  gap: 8px;
}

.group-files {
  background-color: #fff;
}

.group-files .file-list {
  border: none;
  border-radius: 0;
}

/* 面包屑样式优化 */
.el-breadcrumb {
  font-size: 14px;
}

.el-breadcrumb__item:last-child .current-crumb {
  color: #606266;
  cursor: default;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .toolbar {
    gap: 16px;
  }
  
  .path-tag {
    max-width: 150px;
  }
}

@media (max-width: 1024px) {
  .toolbar {
    flex-wrap: wrap;
    gap: 16px;
    padding: 12px 20px;
  }
  
  .toolbar-center {
    order: 3;
    flex-basis: 100%;
    margin-top: 8px;
  }
  
  .app-title {
    font-size: 16px;
  }
  
  .path-tag {
    max-width: 120px;
  }
}

@media (max-width: 768px) {
  .toolbar {
    flex-direction: column;
    gap: 12px;
    align-items: stretch;
    padding: 12px 16px;
  }
  
  .toolbar-left,
  .toolbar-right {
    justify-content: center;
  }
  
  .toolbar-center {
    order: 2;
  }
  
  .app-title {
    font-size: 16px;
    justify-content: center;
  }
  
  .path-tag {
    max-width: none;
    text-align: center;
  }
  
  .main-content {
    flex-direction: column;
    padding: 8px;
    gap: 16px;
  }
  
  .left-panel {
    width: 100% !important;
    max-width: none;
    height: 300px;
  }
  
  .resize-handle {
    display: none;
  }
  
  .status-bar {
    flex-direction: column;
    gap: 4px;
    text-align: center;
  }
}
</style>